import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:word_app/app/modules/model/app_https_client.dart';
import 'package:word_app/app/modules/model/storage_model.dart';
import 'package:word_app/app/modules/model/string_tool.dart';
import 'package:word_app/app/modules/model/toast_model.dart';
import 'package:word_app/app/modules/tabbarVc/views/tabbar_vc_view.dart';

class LoginController extends GetxController {
  late Timer _timer;
  RxBool selectPro = false.obs;
  RxInt remainingTimer = 60.obs;
  TextEditingController phoneTFVc = TextEditingController();
  TextEditingController codeTFVc = TextEditingController();
  AppHttpsClient httpsClient = AppHttpsClient();
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void startTimer() {
    sendCode();
  }

  void selectProAction() {
    selectPro.value = !selectPro.value;
    update();
  }

  Future<void> sendCode() async {
    var response = await httpsClient.post("user/phone/sendCode",
        {"phone": StringTool.removeSapce(phoneTFVc.text)});
    if (response == null) {
    } else {
      if (response.data["code"] == 200) {
        ToastModel.showToast("发送成功");
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          remainingTimer.value = remainingTimer.value - 1;

          if (remainingTimer.value > 0) {
            update();
          }
        });
      } else {
        ToastModel.showToast("发送验证码失败");
      }
    }
  }

  Future<void> loginApp() async {
    var response = await httpsClient.post("user/phone/login",
        {"phone": phoneTFVc.text, "loginType": "code", "code": codeTFVc.text});
    if (response == null) {
    } else {
      if (response.statusCode == 200) {
        if (response.data["code"] == 200) {
          ToastModel.showToast("登录成功");
          StorageModel.setUserModelData(
              "userAllData", jsonEncode(response.data));
          Get.off(const TabbarVcView());
        } else {
          ToastModel.showToast("登录失败");
        }
      } else {}
    }
  }
}
//
